<template>
  <div class="card file-preview">
    <input
      type="file"
      accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      @change="handleFileUpload"
    />
    <div ref="wordContainer" class="word-preview"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import * as docxPreview from "docx-preview";

const wordContainer = ref<HTMLElement | null>(null);

async function handleFileUpload(event: Event) {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file && file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
    const arrayBuffer = await readFileAsArrayBuffer(file);
    loadWordContent(arrayBuffer);
  }
}

// 读取文件为 ArrayBuffer
function readFileAsArrayBuffer(file: File): Promise<ArrayBuffer> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as ArrayBuffer);
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
}

async function loadWordContent(arrayBuffer: ArrayBuffer) {
  const container = wordContainer.value;
  if (container) {
    // 渲染文档
    try {
      await docxPreview.renderAsync(new Uint8Array(arrayBuffer), container, null, {
        className: "custom-word-preview", // 自定义 CSS 类名
        trimXmlDeclaration: true, // 是否去除 XML 声明
        ignoreWidth: true, // 忽略宽度
        ignoreHeight: true, // 忽略高度
        ignoreFonts: false, // 是否忽略字体
        breakPages: false, // 是否分页
        useBase64URL: false, // 使用 Base64 处理图片
        experimental: false // 启用实验性特性
      });
      console.log("Document rendered successfully");
    } catch (err) {
      console.error("Error rendering document:", err);
    }
  } else {
    console.error("wordContainer is not a valid DOM element.");
  }
}

onMounted(() => {
  // 可以在这里添加一些初始化逻辑
});
</script>
<style lang="scss">
.custom-word-preview {
  width: 100%;

  /* color: #333 !important; */
  padding: 76px !important;
  line-height: 1.6 !important;
  background: #fafafa !important;
  border: 1px solid #dddddd !important;
  border-radius: 8px !important;
}
.custom-word-preview span:has(img) {
  display: block !important;
}
.custom-word-preview span div {
  width: 100% !important;
  height: auto !important;
}
.custom-word-preview span div img {
  width: 100% !important;
  height: auto !important;
  border-radius: 4px;
}
</style>
<style lang="scss" scoped>
.file-preview {
  height: 100%;
}
</style>
